package com.lds.config.center.server.client.scheduled;

import com.lds.management.center.common.model.db.PageResult;
import com.lds.management.center.common.model.dto.ResultDTO;
import lombok.Getter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.List;
import java.util.Objects;

public abstract class AbstractInstanceScheduler<T> implements ApplicationRunner {
    @Getter
    private Long id = 0L;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Thread thread = new Thread(() -> {
            while (true) {
                execute();

                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }, "自动通知配置项变更线程");
        thread.setDaemon(true);
        thread.start();
    }

    private void execute() {
        // 分页查询500条
        ResultDTO<PageResult<T>> resultDTO = pageInstances();
        if (!ResultDTO.isSuccess(resultDTO) || Objects.isNull(resultDTO.getData())) return;

        List<T> instances = resultDTO.getData().getData();

        // 如果数据为空 重置查询
        if (CollectionUtils.isEmpty(instances)) {
            id = 0L;
            return;
        }

        // 已经是最后一页
        if (instances.size() < 500) {
            id = 0L;
        } else {
            id = id(instances.get(instances.size() - 1));
        }

        handleInstances(instances);
    }

    protected abstract ResultDTO<PageResult<T>> pageInstances();
    protected abstract Long id(T instance);
    protected abstract void handleInstances(List<T> instances);
}
